package com.tuanzi.loan.business.repository.family.impl;

import com.starbaba.model.dictionary.IStatus;
import com.tuanzi.loan.business.entity.CurrentUser;
import com.tuanzi.loan.business.repository.family.custom.LoanAdvertRepositoryCustom;
import com.tuanzi.loan.core.repository.JOOQBaseRepository;
import com.tuanzi.loan.core.repository.JOOQBaseRepositoryPlus;
import com.tuanzi.loan.core.util.GsonUtils;
import com.tuanzi.loan.generated.jooq.loan.tables.LoanTopicInfo;
import com.tuanzi.loan.generated.jooq.loan.tables.records.LoanTopicInfoRecord;
import com.tuanzi.loan.vo.request.family.LoanAdvertSearchRequest;
import com.tuanzi.loan.vo.response.family.LoanAdvertSearchResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jooq.Condition;
import org.jooq.SelectQuery;
import org.jooq.impl.DSL;
import org.jooq.impl.TableImpl;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Repository;

import java.sql.Timestamp;
import java.util.Date;
import java.util.List;

import static com.tuanzi.loan.generated.jooq.loan.tables.CommSysCode.COMM_SYS_CODE;
import static com.tuanzi.loan.generated.jooq.loan.tables.LoanAdvert.LOAN_ADVERT;
import static com.tuanzi.loan.generated.jooq.loan.tables.LoanProductInfo.LOAN_PRODUCT_INFO;

/**
 * @author weibifeng 2017/09/21
 */
@Repository
@Slf4j
public class LoanAdvertRepositoryImpl extends JOOQBaseRepositoryPlus implements LoanAdvertRepositoryCustom {

	@Override
	protected TableImpl getTable() {
		return LOAN_ADVERT;
	}
	
	/**
	 * 通过活动ID更新所有贷款列表为下线状态
	 */
	@Override
    public Integer offlineByActivityId(Long activityId) {
        return dslContext.update(LOAN_ADVERT)
                .set(LOAN_ADVERT.STATUS,new Short(LoanAdvertStatus.OFFLINE.getValue()))
                .set(LOAN_ADVERT.UTIME,new Timestamp(new Date().getTime()))
                .where(LOAN_ADVERT.ACTIVITY_ID.eq(activityId))
                .execute();
    }

	@Override
	public Page<LoanAdvertSearchResponse> list(LoanAdvertSearchRequest searchRequest, Pageable pageable) {

		Condition condition = DSL.trueCondition();
		if(searchRequest.getPlatform() != null){
			condition = condition.and(LOAN_ADVERT.PLATFORM.contains(searchRequest.getPlatform()));
		}

		if(StringUtils.isNotBlank(searchRequest.getProductId())){
			condition = condition.and(LOAN_ADVERT.PRDID.eq("0").or(LOAN_ADVERT.PRDID.contains(searchRequest.getProductId())));
		}

		if(StringUtils.isNotBlank(searchRequest.getChannel())){
			condition = condition.and(LOAN_ADVERT.CHANNEL.contains(searchRequest.getChannel()));
		}

		if(StringUtils.isNotBlank(searchRequest.getTag())){
			condition = condition.and(LOAN_ADVERT.TAG.contains(searchRequest.getTag()));
		}

		if(searchRequest.getStatus() != null){
			condition = condition.and(LOAN_ADVERT.STATUS.contains(searchRequest.getStatus()));
		}

		if(searchRequest.getAdvertSpace() != null){
			condition = condition.and(LOAN_ADVERT.ADVERT_SPACE.eq(searchRequest.getAdvertSpace()));
		}

		if(StringUtils.isNotBlank(searchRequest.getActivityName())){
			condition = condition.and(LOAN_PRODUCT_INFO.NAME.contains(searchRequest.getActivityName()));
		}

		condition = condition.and(LOAN_ADVERT.SHOW_STATE.eq(1));

		SelectQuery selectQuery =  dslContext.select(LOAN_ADVERT.ID, LOAN_ADVERT.CHANNEL, LOAN_ADVERT.POSITION, LOAN_ADVERT.ACTIVITY_ID,
							LOAN_PRODUCT_INFO.NAME, COMM_SYS_CODE.KINDNAME, LOAN_ADVERT.TAG, LOAN_ADVERT.OPERATOR,
							LOAN_ADVERT.STARTTIME, LOAN_ADVERT.ENDTIME, LOAN_ADVERT.STATUS)
				.from(LOAN_ADVERT)
				.leftJoin(LOAN_PRODUCT_INFO).on(LOAN_PRODUCT_INFO.ID.eq(LOAN_ADVERT.ACTIVITY_ID))
				.leftJoin(COMM_SYS_CODE).on(COMM_SYS_CODE.CODE.eq(LOAN_ADVERT.ADVERT_SPACE).and(COMM_SYS_CODE.TYPE.eq("advertise")))
				.where(condition)
				.orderBy(LOAN_ADVERT.POSITION)
				.getQuery();


		return search(selectQuery, pageable, record -> {

			LoanAdvertSearchResponse response = new LoanAdvertSearchResponse();
			response.setId(record.get(LOAN_ADVERT.ID));
			response.setChannel(record.get(LOAN_ADVERT.CHANNEL));
			response.setPosition(record.get(LOAN_ADVERT.POSITION,Integer.class));
			response.setActivityId(record.get(LOAN_ADVERT.ACTIVITY_ID, Integer.class));
			response.setActivityName(record.get(LOAN_PRODUCT_INFO.NAME));
			response.setAdvertSpace(record.get(COMM_SYS_CODE.KINDNAME));
			response.setTag(record.get(LOAN_ADVERT.TAG));
			response.setOperator(record.get(LOAN_ADVERT.OPERATOR));
			response.setStartTime(record.get(LOAN_ADVERT.STARTTIME) == null ? "" : record.get(LOAN_ADVERT.STARTTIME).toString());
			response.setEndTime(record.get(LOAN_ADVERT.ENDTIME) == null ? "" : record.get(LOAN_ADVERT.ENDTIME).toString());
			response.setStatus(record.get(LOAN_ADVERT.STATUS, Integer.class));
			return response;
		});

	}

	@Override
	public void delete(Integer id) {
		dslContext.delete(LOAN_ADVERT).where(LOAN_ADVERT.ID.eq(id.longValue())).execute();
	}

	@Override
	public void changeStatus(Integer id) {
		Integer status = dslContext.select(LOAN_ADVERT.STATUS).from(LOAN_ADVERT).where(LOAN_ADVERT.ID.eq(id.longValue())).fetchOneInto(Integer.class);
		status=(status ==0 ? 1:0);
		if(status != null && status.equals(1)){
			log.info("用户" + CurrentUser.get().getName() + "下线广告位产品：" + id);
		}

		dslContext.update(LOAN_ADVERT).set(LOAN_ADVERT.STATUS,status.shortValue()).where(LOAN_ADVERT.ID.eq(id.longValue())).execute();
	}

	@Override
	public void updatePosition(Integer position, Integer id) {
		dslContext.update(LOAN_ADVERT).set(LOAN_ADVERT.POSITION,position).where(LOAN_ADVERT.ID.eq(id.longValue())).execute();
	}

	@Override
	public List<LoanTopicInfoRecord> gettopicList() {
		List<LoanTopicInfoRecord> fetch = dslContext.select(LoanTopicInfo.LOAN_TOPIC_INFO.ID).from(LoanTopicInfo.LOAN_TOPIC_INFO).
				where(LoanTopicInfo.LOAN_TOPIC_INFO.STATUS.eq(IStatus.VALIDATE)).fetchInto(LoanTopicInfoRecord.class);
		return fetch;
	}
}
